package com.yc154.web;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

@Component
public class CustomLoggingGatewayFilterFactory
        extends AbstractGatewayFilterFactory< CustomLoggingGatewayFilterFactory.Config > {
    private static final Logger log =
            LoggerFactory.getLogger(CustomLoggingGatewayFilterFactory.class);
    // 构造函数，告诉父类使用哪个配置类
    public CustomLoggingGatewayFilterFactory() {
        super(Config.class);
    }
    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            // 前置处理：记录开始时间
            long startTime = System.currentTimeMillis();
            log.info("Pre Filter: Request to {}", exchange.getRequest().getURI());
            // 后置处理：在 chain.filter 之后（即后端服务返回后）记录耗时
            return chain.filter(exchange).then(Mono.fromRunnable(() -> {
                long duration = System.currentTimeMillis() - startTime;
                log.info("Post Filter: Request to {} took {} ms",
                        exchange.getRequest().getURI(), duration);
                if (config.isLogHeaders()) {
                    // 根据配置决定是否打印Header
                    log.info("Response Headers: {}", exchange.getResponse().getHeaders());
                }
            }));
        };
    }
    // 定义配置类，用于接收配置文件中的参数
    public static class Config {
        private boolean logHeaders = false;
        public boolean isLogHeaders() {
            return logHeaders;
        }
        public void setLogHeaders(boolean logHeaders) {
            this.logHeaders = logHeaders;
        }
    }
    @Override
    public String name() {
        // 这个名字很重要，用于在配置文件中引用这个过滤器
        return "CustomLogging";
    }
}
